#include "ballclock.h"

linkqueue_t *init_linkqueue()
{
    linkqueue_t *q = NULL;
    linknode_t *head = NULL;

    head = (linknode_t *)malloc(sizeof(linknode_t));
    if (NULL == head)
    {
        printf("malloc failed!\n");
        return NULL;
    }
    memset(head, 0, sizeof(linknode_t));
    head->next = NULL;


    q = (linkqueue_t *)malloc(sizeof(linkqueue_t));
    if (NULL == q)
    {
        printf("malloc failed!\n");
        return NULL;
    }
    memset(q, 0, sizeof(linkqueue_t));
    q->front = q->rear = head;
    return q;
}

int is_empty_linkqueue(linkqueue_t *q)
{
    return q->front == q->rear ? 1 : 0;
}

void enter_linkqueue(linkqueue_t *q, data_t data)
{
    linknode_t *temp = NULL;
    temp = (linknode_t *)malloc(sizeof(linknode_t));
    if (NULL == temp)
    {
        printf("malloc failed!\n");
        return;
    }

    temp->data = data;
    temp->next = q->rear->next;
    q->rear->next = temp;

    // 更新尾指针
    q->rear = temp;
    return;
}

data_t delete_linkqueue(linkqueue_t *q)
{
    linknode_t *temp = NULL;
    data_t data = 0;

    temp = q->front->next;
    data = temp->data;

    q->front->next = temp->next;
    free(temp);
    temp == NULL;

    if (q->front->next == NULL)
    {
        q->rear = q->front;
    }

    return data;
}